package cn.javabb.project.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.javabb.common.constant.ConsVal;
import cn.javabb.common.exception.DBException;
import cn.javabb.common.exception.GenException;
import cn.javabb.framework.model.GenModel;
import cn.javabb.framework.util.DBUtil;
import cn.javabb.project.entity.*;
import cn.javabb.project.mapper.GenTableMapper;
import cn.javabb.project.util.GenUtil;
import cn.javabb.project.util.VelocityUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: javabb (javabob(a)163.com)
 * @create: 2021/03/26 18:12
 */
@Slf4j
@Service
public class GenTableService extends ServiceImpl<GenTableMapper, GenTable> {

    @Autowired
    GenTableColumnService genTableColumnService;

    public List<GenTable> list(GenTable table) {
        List<GenTable> list = baseMapper.listTable(table);
        return list;
    }

    public List<GenTable> listWithColumnsByProjectId(String projectId) {
        GenTable query = new GenTable();
        query.setProjectId(projectId);
        List<GenTable> list = baseMapper.listTable(query);
        list.parallelStream().forEach(table->{
            List<GenTableColumn> columns = genTableColumnService.listByTableId(table.getTableId());
            table.setColumns(columns);
        });
        return list;
    }

    @Transactional
    public boolean updateTable(GenTable table) {

        table.setUpdateTime(new Date());
        boolean ret = this.updateById(table);
        if (ret) {
            genTableColumnService.saveOrUpdateBatch(table.getColumns());
        }
        return ret;
    }
    @Transactional
    public boolean deleteTable(String tableId) {

        boolean ret = this.removeById(tableId);
        if (ret) {
            genTableColumnService.deleteByTableId(tableId);
        }
        return ret;
    }

    public void deleteByProjectId(String projectId) {
        QueryWrapper<GenTable> query = new QueryWrapper<>();
        query.eq("project_id" , projectId);
        List<GenTable> list = this.list(query);
        List<String> tableIds = list.stream().map(t -> t.getTableId()).collect(Collectors.toList());
        if (this.remove(query)) {
            genTableColumnService.deleteByTableIds(tableIds);
        }
    }
}
